package com.qsign.sfrz_android.activity.home.ViewController;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.device.ScanDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.google.gson.Gson;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.qsign.sfrz_android.R;
import com.qsign.sfrz_android.activity.login.Model.MyUserData;
import com.qsign.sfrz_android.base.AppManager;
import com.qsign.sfrz_android.base.MyApplication;
import com.qsign.sfrz_android.base.NewBaseActivity;
import com.qsign.sfrz_android.base.YcspUserDataShared;
import com.qsign.sfrz_android.mainmodel.UpdateBean;
import com.qsign.sfrz_android.net.IServiceImpl;
import com.qsign.sfrz_android.net.RequestServiceImpl;
import com.qsign.sfrz_android.utils.ToolUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends NewBaseActivity {

    @BindView(R.id.namelab)
    TextView namelab;

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void initTitle(TextView textView) {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        MyUserData userData=  YcspUserDataShared.getInstance(MyApplication.getInstance()).getUserdata();
        namelab.setText(userData.getXM());

        RequestServiceImpl.update(mMIPHandler, IServiceImpl.UPDATEAUTO);
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        switch (requestType) {
            case IServiceImpl.UPDATEAUTO://根据条件查询
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONObject updatejson = jsonObject.getJSONObject("DATA");
                        if (updatejson != null) {
                            Gson gson = new Gson();
                            final UpdateBean userBean = gson.fromJson(updatejson.toJSONString(), UpdateBean.class);
                            if (!userBean.getAndroidversionCode().equals(ToolUtils.getVerName(MainActivity.this))) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        UIData uiData = UIData.create();
                                        uiData.setTitle(userBean.getAndroidversionName());
                                        uiData.setDownloadUrl(userBean.getAndroidUrl());
                                        uiData.setContent("发现新版本，请更新后使用");
                                        uiData.setForce(true);
                                        DownloadBuilder builder = AllenVersionChecker
                                                .getInstance()
                                                .downloadOnly(uiData);
                                        //  builder.setCustomVersionDialogListener(createCustomDialog());
                                        builder.setNotificationBuilder(createCustomNotification());
                                        builder.setShowNotification(true);
                                        builder.setForceRedownload(true);
                                        builder.setShowDownloadingDialog(false);
                                        builder.setApkDownloadListener(new APKDownloadListener() {
                                            KProgressHUD hud = null;

                                            @Override
                                            public void onDownloading(int progress) {
                                                if (hud == null) {
                                                    hud = KProgressHUD.create(AppManager.getAppManager().currentActivity())
                                                            .setStyle(KProgressHUD.Style.ANNULAR_DETERMINATE)
                                                            .setLabel("正在更新")
                                                            .setCancellable(false)
                                                            .setMaxProgress(100).show();
                                                }
                                                hud.setProgress((int) progress);
                                            }

                                            @Override
                                            public void onDownloadSuccess(File file) {
                                                hud.dismiss();
                                            }

                                            @Override
                                            public void onDownloadFail() {
                                            }
                                        });
                                        builder.executeMission(AppManager.getAppManager().currentActivity());
                                    }
                                });

                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("ddd",e.toString());
                }

                break;
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        //返回键回到桌面
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @OnClick({R.id.fuhebtn, R.id.rukubtn, R.id.chukubtn, R.id.pihaobtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fuhebtn:
                Intent intent = new Intent(this, ScanFuheActivity.class);
                startActivity(intent);
                break;
            case R.id.rukubtn:
                Intent intent2 = new Intent(this, RukuActivity.class);
                startActivity(intent2);
                break;
            case R.id.chukubtn:
                Intent intent3 = new Intent(this, ChuKuMainActivity.class);
                startActivity(intent3);
                break;
            case R.id.pihaobtn:
                Intent intent4 = new Intent(this, PiHaoActivity.class);
                startActivity(intent4);
                break;
        }
    }



    private static NotificationBuilder createCustomNotification() {
        String appname = "";
        try {
            PackageManager packageManager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            appname = String.valueOf(packageManager.getApplicationLabel(MyApplication.getInstance().getApplicationContext().getApplicationInfo()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NotificationBuilder.create()
                .setRingtone(true)
                // .setIcon(R.mipmap.dialog4)
                .setTicker(appname)
                .setContentTitle(appname)
                .setContentText("%d%%/100%%");
    }
}
